package com.example.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @Description: 基础文件上传接口:
 * @Date：Create in 2024-12-05 15:09
 * @Author: 刘雨
 */
public class UploadUtils {

    private static final Logger log = LoggerFactory.getLogger(UploadUtils.class);

    // 专项工程-附件上传地址：
    public static final String FILE_UPLOAD_PATH = "\\file\\upload\\bridge";
    public static final String FILE_UPLOAD_NETWORK_PATH = "/file/upload/bridge";


    /**
     * 文件上传:
     * @param files
     */
    //public String uploadFile(MultipartFile[] files, HttpServletRequest request, String filePath) {
    public String uploadFile(MultipartFile[] files, HttpServletRequest request) {
        // 返回结果字符窜:
        StringBuilder urlBunch = new StringBuilder();

        String path = request.getContextPath();
        // 本地项目绝对测试地址：
        String projectPath = System.getProperty("user.dir") + UploadUtils.FILE_UPLOAD_PATH;
        this.mkVlidate(projectPath);

        // 服务器Windows:
        String windoswsPath = System.getProperty("os.name");
        String windoswsPath_1 = System.getProperty("os.name").toLowerCase().startsWith("win") + "";
        log.info("服务器是{}", windoswsPath);


        // 网络地址：
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        String uploadUrl = basePath + UploadUtils.FILE_UPLOAD_NETWORK_PATH;
        this.mkVlidate(uploadUrl);

        if(!ArrayUtils.isEmpty(files)) {
            for (MultipartFile file : files) {
                // 记录地址串：
                if (!"".equals(file.getOriginalFilename())) {
                    String originalFilename = file.getOriginalFilename();
                    // 设置本地地址
                    String newFilePath = projectPath + "/" + originalFilename;
                    // 设置网络地址
                    // String newFilePath = uploadUrl + "/" + originalFilename;
                    urlBunch.append(newFilePath).append(",");

                    try {
                        File newFile = new File(newFilePath);
                        file.transferTo(newFile);

                        log.info(newFile.exists() ? newFile.getAbsolutePath() : "此选项没有提交文件!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return urlBunch.length() != 0 ? urlBunch.substring(0, urlBunch.length() - 1 - 1) : null;
    }


    public void mkVlidate(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }else{
            log.info("文件目录'"+ path +"'已存在!");
        }
    }

}
